package com.happe.foodeasy.manage.interceptor;

import com.happe.foodeasy.manage.dto.ManagerLoginDTO;
import com.happe.foodeasy.manage.common.entity.ManagerEntity;
import com.happe.foodeasy.manage.service.ManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is one interceptor that is used to intercept the request and check whether
 * the user has login on or not.
 * Created by wubin on 2016-07-10.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private ManagerService managerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ManagerEntity currentManager = (ManagerEntity) request.getSession().getAttribute("currentManager");
        String contextPath = request.getContextPath();
        String contextUri = request.getRequestURI();
        String url = contextUri.substring(contextPath.length() + 1);

        if (currentManager == null) {
            ManagerLoginDTO dto = new ManagerLoginDTO();

            Cookie[] cookies = request.getCookies();
            for (Cookie oneCookie : cookies) {
                if (oneCookie.getName().equals("username")) {
                    dto.setUsername(oneCookie.getValue());
                }

                if (oneCookie.getName().equals("password")) {
                    dto.setPassword(oneCookie.getValue());
                }
            }
            if (dto.getUsername() != null && dto.getPassword() != null) {
                ManagerEntity resultManager = managerService.checkManagerExist(dto);
                if (resultManager != null) {
                    request.getSession().setAttribute("currentManager", resultManager);
                    return true;
                }
            }
            logger.info("url: " + url);
            request.getSession().setAttribute("requestTarget", url);
            response.sendRedirect(contextPath + "/login-in.jsp");
            return false;
        }

        return true;
    }
}
